package servicex

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"zhonghui/console/warehouse/dbx/cache_main"
	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/logx"
)

const uniqueSeqRedisKey = "unique_seq_k"

// MakeUniqueSeqByRedis 创建12位全局唯一序列号
func MakeUniqueSeqByRedis(c context.Context) (string, error) {
	var seq int64
	seq = cache_main.Client().IncrBy(context.Background(), uniqueSeqRedisKey, rand.Int63n(100)+1).Val()
	if seq < 100000000000 {
		logx.ZapTrace(c).Errorw("seq重置了", "err", errors.New("seq has been reset"))
		seq = cache_main.Client().IncrBy(context.Background(), uniqueSeqRedisKey, 203024002002+rand.Int63n(1000000)).Val()
	}

	if seq < 100000000000 {
		logx.ZapTrace(c).Errorw("seq又重置了", "err", errors.New("seq has been reset"))
		return "", errors.New("seq reset fail")
	}

	return strconv.FormatInt(seq, 10), nil
}

// MakeUniqueTradeNo24 生成订单号
// 如 年4位+月2位+日2位+seq12位+0000，共计24位
// 如传递uid，则会生成
// 如 年4位+月2位+日2位+seq12位+uid后4位（不足前置补0），共计24位
func MakeUniqueTradeNo24(c context.Context, uid uint64) string {
	seq, err := MakeUniqueSeqByRedis(c)
	if err != nil {
		return ""
	}

	u := ""
	uidStr := strconv.FormatUint(uid, 10)
	if len(uidStr) > 4 {
		u = uidStr[len(uidStr)-4:]
	} else {
		u = uidStr
	}
	return fmt.Sprintf("%s%s%04s", time.Now().Format(helperx.TimeLayoutUYmd), seq, u)
}

// MakeUniqueTradeNo20 生成订单号
// 如 年4位+月2位+日2位+seq12位，共计20位
func MakeUniqueTradeNo20(c context.Context) string {
	seq, err := MakeUniqueSeqByRedis(c)
	if err != nil {
		return ""
	}

	return fmt.Sprintf("%s%s", time.Now().Format(helperx.TimeLayoutUYmd), seq)
}
